<template>
  <div class="performance-list-container scroll-y" v-loading.fullscreen="loading" >
    <form ref="tableHeaderContainer" class="base-search" onsubmit="return false;">
      <div class="search-group input-with-append-search">
        <el-input v-model="params.keyword" :placeholder="$t('performance.placeholder.inputName')">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
           <el-button slot="append" type="primary" @click="search(true);trackEventHandler('search')" native-type="submit">{{$t('common.base.search')}}</el-button>
        </el-input>
        <el-button type="plain-third" @click="reSearch" class="ml_12">{{$t('common.base.reset')}}</el-button>
      </div>
      <span class="advanced-search-visible-btn" @click.stop="advancedSearchPanelShow = !advancedSearchPanelShow;trackEventHandler('advSearch')">
        <i class="iconfont icon-filter"></i>
        {{$t('common.base.advancedSearch')}}
      </span>
    </form>

    <!--高级搜索-->
    <base-panel :show.sync="advancedSearchPanelShow" width="420px">
      <h3 slot="title">
        <span>{{$t('common.base.advancedSearch')}}</span>
      </h3>
      <el-form label-position="top" class="advanced-search-form" onsubmit="return false;">
        <el-form-item :label="$t('performance.label.type')">
          <el-select v-model="secondaryParams.type" :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in rangeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('performance.label.status')">
          <el-select v-model="secondaryParams.status" :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in statusOptions"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.rulerName')">
          <el-select v-model="secondaryParams.ruleIds" :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in openRules"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.createTime')">
          <el-date-picker
            v-model="secondaryParams.time"
            type="daterange"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
            align="right"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            :picker-options="createTimePickerOptions">
          </el-date-picker>
        </el-form-item>
        <div class="advanced-search-btn-group">
          <el-button type="plain-third" @click="reSearch">{{$t('common.base.reset')}}</el-button>
          <el-button type="primary" @click="search(true)" native-type="submit">{{$t('common.base.search')}}</el-button>
        </div>
      </el-form>
    </base-panel>

    <div class="performance-list">
      <div ref="tableDoContainer" class="operation-bar-container">
        <div class="top-btn-group flex-x">
          <el-button type="primary" icon="el-icon-plus" @click="openDialog">{{$t('common.base.create')}}</el-button>
          <el-button type="plain-third" @click="deleteReport">
            <i class="iconfont icon-delete task-font14"></i>
            {{$t('common.base.delete')}}
          </el-button>
          <a :href="performanceReportLink" target="_blank" style="color:#576B95;" class="ml_12">{{$t('performance.tip.linkTip')}}</a>
        </div>


        <div class="action-button-group flex-x bg-w">
          <el-dropdown trigger="click" v-if="isButtonDisplayed && exportAuth">
            <span class="el-dropdown-link cur-pointer" @click="trackEventHandler('moreAction')">
              {{$t('common.base.moreOperator')}}
              <i class="iconfont icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportReport(false)">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportReport(true)">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>


          <!-- <el-dropdown :hide-on-click="false" :show-timeout="150" trigger="click">
            <span class="el-dropdown-link cur-pointer" @click="trackEventHandler('selectColumn')">
              选择列
              <i class="iconfont icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="customer-columns-dropdown-menu">
              <el-dropdown-item v-for="(item, index) in columns" :key="`${item.field}_${index}`">
                <el-checkbox :value="item.show" @input="modifyColumnStatus($event, item)" :label="item.label"/>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
              <!-- 选择列 -->
          <div class="guide-box">
            <div :class="[
                   'task-ai',
                   'task-flex',
                   'task-font14',
                   'task-c6',
                   'cur-point',
                   'task-width103',
                 ]"
                 @click="showAdvancedSetting">
              <span class="task-mr4">{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>

        </div>


      </div>

    <div id="report-list-1"  class="bg-w pad-l-16 pad-r-16">
      <el-table
        :data="tableData"
        :row-key="getRowKey"
        :key="tableKey"
        stripe
        border
        @select="handleSelection"
        @select-all="handleSelection"
        :height="tableContainerHeight"
        ref="multipleTable" class="report-table bbx-normal-list-box">
        
        <template slot="empty">
          <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        </template>

        <el-table-column type="selection" width="48" align="center"></el-table-column>
        <el-table-column
          v-for="(column, index) in columns"
          v-if="column.show"
          :key="`${column.field}_${index}`"
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :fixed="!!column.fixLeft"
          :show-overflow-tooltip="getPerformanceShowTooltip(column)"
        >
          

          <template slot-scope="scope">
            <template v-if="column.field === 'cycle'">
              {{scope.row.startTime}} ~ {{scope.row.endTime}}
            </template>
            
            <template v-else-if="column.field === 'createUser'">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.createUserStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.createUser }}
              </template>
            </template>
            
            <template v-else-if="column.field === 'carbonCopy'">
              <template v-if="isOpenData">
                <template v-for="(item, index) in scope.row.carbonCopyStaffIds">
                  <open-data :key="`${item}${uuid()}`" type="userName" :openid="item"></open-data>
                  <ui-separator :index="index" :list="scope.row.carbonCopyStaffIds" :key="`${item}${uuid()}`" />
                </template>
              </template>
              <template v-else>
                {{ scope.row.carbonCopy }}
              </template>
            </template>
            
            <template v-else-if="column.field === 'users'">
              <template v-if="isOpenData && scope.row.userStaffId">
                <template v-for="(item, index) in scope.row.userStaffIdsArray">
                  <open-data :key="`${item}${uuid()}`" type="userName" :openid="item"></open-data>
                  <ui-separator :index="index" :list="scope.row.userStaffIdsArray" :key="`${item}${uuid()}`" />
                </template>
              </template>
              <template v-else>
                {{ scope.row.users }}
              </template>
            </template>
            
            <template v-else-if="column.field === 'action'">
              <el-button plain @click="viewDetail(scope.row)" size="small">{{$t('common.base.view')}}</el-button>
            </template>
            <template v-else-if="column.field === 'status'">

              {{scope.row[column.field]}}
              <el-tag size="mini" v-if="scope.row.waitingForApprove">{{$t('common.base.usualStatus.approving')}}</el-tag>
            </template>
            <template v-else>
              {{scope.row[column.field]}}
            </template>
          </template>
        </el-table-column>

      </el-table>
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span class="level-padding" place="count">{{ params.totalItems || 0 }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span class="performance-selected-count" @click="panelTheMultipleSelectionShow = true" place="count">{{ multipleSelection.length }}</span>
            </i18n>
            <span class="performance-selected-count" @click="selectionInit()">{{$t('common.base.clear')}}</span>
          </template>
        </div>

        <el-pagination
          class="performance-report-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableDatas"
          :page-size="params.pageSize"
          :current-page="params.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="params.totalItems">
        </el-pagination>
      </div>
    </div>

    </div>

    <!-- start 后台任务列表 -->
    <edit-performance-report-dialog 
      :init-data="initData" 
      @refresh-list="search" 
      ref="reportDialog" 
    />
    <!-- end 后台任务列表 -->

    <!-- start 已选择列表 -->
    <base-panel class="performance-panel" :show.sync="panelTheMultipleSelectionShow" width="420px">
      <h3 slot="title">
        <i18n path="performance.title.selectCount">
          <span place="length">{{ multipleSelection.length }}</span>
        </i18n>
        <i 
          v-if="multipleSelection.length > 0"
          class="iconfont icon-qingkongshanchu performance-panel-btn" 
          @click="selectionInit()" 
          :title="$t('common.base.tip.clearChoseDataTip')" data-placement="right" v-tooltip></i>
      </h3>

      <div class="performance-selected-panel">
        <div class="performance-selected-tip" v-if="multipleSelection.length <= 0">
          <img :src="noDataImage">
          <p>{{$t('common.base.tip.noSelectedDataFromList')}}</p>
        </div>
        <template v-else>
          <div class="performance-selected-list">
            <div class="performance-selected-row performance-selected-head">
              <span class="performance-selected-type">{{$t('common.base.type')}}</span>
              <span class="performance-selected-name">{{$t('common.base.name')}}</span>
            </div>
            <div class="performance-selected-row" v-for="item in multipleSelection" :key="item.id" >
              <span class="performance-selected-type">{{ item.type }}</span>
              <span class="performance-selected-name">{{ item.reportName }}</span>
              <button type="button" class="performance-selected-delete" @click="selectPerformanceCancel(item)">
                <i class="iconfont icon-fe-close"></i>
              </button>
            </div>
          </div>
        </template>
      </div>
    </base-panel>
    <!-- end 已选择列表 -->

    <base-export
      ref="exportPanel"
      :columns="columns"
      :build-params="buildExportParams"
      method="post"
      :action="performanceListExport"/>
      <!--:validate="checkExportCount"-->

    <!-- 选择列公共组件 -->
    <biz-select-column ref="advanced" @save="saveColumnStatus" />

  </div>
</template>

<script>
import { getRootWindowInitData } from '@src/util/window'
import _ from 'lodash';
import {getPerformanceReports, deletePerformanceReports, getApprovePersonList} from '@src/api/PerformanceApi';
import EditPerformanceReportDialog from './components/EditPerformanceReportDialog.vue';
import Platform, { isOpenData, openAccurateTab } from '@src/util/platform.ts'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { checkButtonDisplayed } from '@src/util/dom';

import StorageUtil from '@src/util/storage.ts';
import StorageKeyEnum from '@model/enum/StorageKeyEnum';
import StorageModuleEnum from '@model/enum/StorageModuleEnum';


/* export & import */
import { performanceListExport } from '@src/api/Export';
import { isEmpty } from '@src/util/type';
import { defaultTableData } from '@src/util/table'

import {
  mergeFieldsWithProperty,
  getFieldName
} from '@service/FieldService.ts';

import { safeNewDate } from '@src/util/time';
import { formatDate, useFormTimezone, useDatePicker } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
const datePicker = useDatePicker()
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
import { t } from '@src/locales';
export default {
  name: 'list-view',
  mixins: [ThemeMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({}),
    }
  },
  data() {
    return {
      defaultTableData,
      noDataImage,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      advancedSearchPanelShow: false,
      createTimePickerOptions: {
        shortcuts: [
          datePicker.nearDate(t('common.time.lastWeek'), 1, 'week'),
          datePicker.nearDate(t('common.time.lastMonth'), 1, 'month'),
          datePicker.nearDate(t('common.time.lastThreeMonth'), 3, 'month'),
        ]
      },
      loading: false,
      columns: [],
      multipleSelection: [],
      reports: [],
      rangeOptions: [
        {
          label: t('common.base.all'),
          value: 995,
        },
        {
          label: t('common.base.allowPerson'),
          value: 0,
        },
        {
          label: t('common.base.allowDepartment'),
          value: 1,
        },
      ],
      statusOptions: [
        {
          label: t('common.base.all'),
          value: '',
        },
        {
          label: t('common.base.usualStatus.hasCreated'),
          value: '0',
        },
        {
          label: t('common.base.usualStatus.approved'),
          value: '1,3',
        },
        {
          label: t('common.base.usualStatus.released'),
          value: '4',
        },
      ],
      params: {
        keyword: '',
        time: '',
        type: 995,
        pageNum: 1,
        pageSize: 10,
        totalItems: 0,
        ruleIds: '',
      },
      secondaryParams: {
        time: '',
        type: 995,
        ruleIds: '',
      },
      selectedLimit: 200,
      userList: [],
      panelTheMultipleSelectionShow: false,
      performanceListExport,
      tableContainerHeight:'440px',
      tableKey: (Math.random() * 1000) >> 2,
    }
  },
  computed: {
    // 处理时间后的列表数据
    tableData(){
      return disposeFormListViewTime(this.reports, this.columns)
    },
    tenantType() {
      return getRootWindowInitData()?.tenantType;
    },
    openRules() {
      return (this.initData.AllOpenRules || [])
        .map(({id, ruleName, ruleDesc}) => ({
          label: ruleName,
          value: id,
          ruleDesc,
        }));
    },
    userId () {
      return this.initData.loginUserId;
    },
    // 是否在钉钉环境
    isDingTalk() {
      return Platform.isDingTalk()
    },
    // 绩效报告介绍链接
    performanceReportLink() {
      let url = ''
      if(this.tenantType == 2) {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/gyxk70hkoch0a4pl/el96sy4cshlth7vk.html'
      } else if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcnEK4O4CsqmgVQlA0Uu4x7Pc'
      } else {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/gyxk70hkoch0a4pl/el96sy4cshlth7vk.html'
      } 
      return url
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data')) || {}
      return initData.auths?.PERFORMANCE_RECORD_EXPORT || 0
    }
  },
  mounted() {
    this.buildColumns()

    const localStorageData = this.getLocalStorageData();

    if (localStorageData.pageSize) {
      this.params.pageSize = Number(localStorageData.pageSize);
    }

    this.search();
    let that_ = this;
    // 监听切换后需要重新计算列表高度
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
  },
  methods: {
    exportReport(exportAll) {
      let ids = [];
      let fileName = t('performance.title.exportFileName2', {date: formatDate(safeNewDate(), 'YYYY-MM-DD')});
      if (!exportAll) {
        if (!this.multipleSelection.length) return this.$platform.alert(t('common.base.tip.exportNoChoice'));
        ids = this.multipleSelection.map(({id}) => id);
      }

      let isExportDownloadNow = true;
      this.$refs.exportPanel.open(ids, fileName, isExportDownloadNow);
    },
    buildExportParams(checkedArr, ids) {
      let exportAll = !ids || !ids.length;

      if (exportAll) {
        return {
          checked: `${checkedArr.join(',') },`,
          // exportSearchModel: exportAll ? JSON.stringify(this.buildParams() || {}) : ''
        };
      }

      return {
        checked: `${checkedArr.join(',') },`,
        ids: `${ids.join(',') },`,
      };
    },

    search(fullSearch) {
      if (fullSearch) {
        this.params = {
          ...this.params,
          ...this.secondaryParams,
          pageNum: 1,
        }
      }

      let params = this.buildParams();
      this.loading = true;

      getPerformanceReports(params)
        .then(res => {
          this.loading = false;
          if (!res || res.status) {
            return this.$platform.notification({
              title: t('common.base.fail'),
              message: (h => (<div>{res.message || t('performance.tip.getPerformanceDataError')}</div>))(this.$createElement),
              type: 'error',
            });
          }

          if (!res.data.reportList) {
            this.reports = [];
            this.params.totalItems = 0;
            return;
          }
          this.reports = res.data.reportList.list
            .map(({users, createUserName, userStaffId, createTime, startTime, endTime, type, reportName, ruleIds, id, carbonCopy, carbonCopyStaffId, status, createUser, createUserStaffId}) => Object.freeze({
              reportName,
              ruleIds: ruleIds.replace(/\[|\]/g, ''),
              users: users.replace(/\[|\]/g, ''),
              userStaffId: userStaffId ? userStaffId.replace(/\[|\]/g, '') : '',
              userStaffIdsArray: userStaffId ? userStaffId.replace(/\[|\]/g, '').split(',') : [],
              createUser: createUserName,
              createUserStaffId,
              createUserId: createUser,
              createTime: formatDate(createTime, 'YYYY-MM-DD'),
              startTime: formatDate(startTime, 'YYYY-MM-DD'),
              endTime: formatDate(endTime, 'YYYY-MM-DD'),
              type: type ? t('common.base.allowDepartment') : t('common.base.allowPerson'),
              id,
              carbonCopy: carbonCopy ? carbonCopy.replace(/\[|\]|"/g, '') : '',
              carbonCopyStaffIds: carbonCopyStaffId ? carbonCopyStaffId.split(',') : [],
              waitingForApprove: status === 1,
              status: (() => {
                if (status === 0 || status === 1) {
                  return t('common.base.usualStatus.hasCreated')
                }

                if (status === 3) {
                  return t('common.base.usualStatus.approved')
                }
                if (status === 4) {
                  return t('common.base.usualStatus.released')
                }

              })()
            }));
          this.params.totalItems = res.data.reportList.total;
          // 把已选中的匹配出来
          this.matchSelected();
        })
        .catch(e => console.error('e', e));

    },
    buildParams() {
      const {keyword, pageNum, pageSize, time, type, ruleIds, status} = this.params;
      let params = {
        pageNum,
        pageSize,
      };

      if (ruleIds) {
        params.ruleIds = ruleIds;
      }

      if (keyword) {
        params.reportName = keyword;
      }

      if (time) {
        const [startTime, endTime] = time || []
        params.startTime = startTime;
        params.endTime = endTime
      }

      if (type !== 995) {
        params.type = type;
      }

      params.status = status || '';
      // params.status = status ? status.join(',') : '';

      return params;
    },
    reSearch() {
      window.TDAPP.onEvent('pc：绩效报告-重置事件');
      this.resetParams();
      this.search();
    },
    viewDetail(row) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `performanceReport${row.id}`,
      //   title: '绩效报告详情',
      //   close: true,
      //   url: `/performance/v2/report/desc/${row.id}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePerformanceReport,
        key: row.id,
        titleKey: t('common.pageTitle.pageReportDesc'),
        fromId
      })
    },
    openDialog() {
      window.TDAPP.onEvent('pc：绩效报告-新建事件');
      this.$refs.reportDialog.toggleDialog();
    },
    /**  
     * @description 操作选中
    */
    handleSelection(selection) {
      let selected = this.selectionComputed(selection);
      let currentPageSelected = this.multipleSelection.filter(ms => {
        return this.reports.some(report => report.id === ms.id)
      });
      let currentPageUnSelected = this.reports.filter(repost => {
        return currentPageSelected.every(currentPageItem => repost.id !== currentPageItem.id);
      })

      if (selected.length > this.selectedLimit) {
        this.$nextTick(() => {
          currentPageSelected.length > 0
          ? currentPageUnSelected.forEach(unSelected => {
              this.$refs.multipleTable.toggleRowSelection(unSelected, false);
            })
          : this.$refs.multipleTable.clearSelection();
        })

        return this.$platform.alert(t('common.base.tip.choiceLimit', {limit: this.selectedLimit}));
      }
      this.multipleSelection = selected;
    },
    /**  
     * @description 计算选中
    */
    selectionComputed(selection) {
      let preSelected = this.multipleSelection.filter(ms => {
        return this.reports.every(report => report.id !== ms.id);
      })

      preSelected = _.uniqWith([...preSelected, ...selection], _.isEqual);

      return preSelected;
    },
    jump(pageNum) {
      this.params.pageNum = pageNum;
      this.search();
    },
    handleSizeChange(pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.params.pageNum = 1;
      this.params.pageSize = pageSize;
      this.search();
    },
    async deleteReport() {
      window.TDAPP.onEvent('pc：绩效报告-删除事件');
      if (!this.multipleSelection.length) {
        return this.$platform.alert(t('performance.tip.deletePerformanceTip'));
      }

      const pass = this.reports.filter(r => this.multipleSelection.some(item => item.id === r.id))
        .some(r => r.createUserId !== this.userId || r.waitingForApprove);

      if (pass) return this.$platform.alert(t('performance.tip.deletePerformanceTip2'));

      try {
        if (!await this.$platform.confirm(t('performance.tip.deletePerformanceTip3'))) return;

        deletePerformanceReports({
          ids: `${this.multipleSelection.map(({id}) => id).join(',') },`,
        })
          .then(res => {
            if (res.status) {
              return this.$platform.notification({
                title: t('common.base.fail'),
                message: (h => (<div>{res.message || t('common.base.tip.unknownError2')}</div>))(this.$createElement),
                type: 'error',
              });
            }

            this.multipleSelection = [];
            this.search();
          })
          .catch(err => console.error('deleteCustomer err', err));
      } catch (e) {
        console.error('catch error', e);
      }
    },
    resetParams() {
      this.params = {
        ...this.params,
        keyword: '',
        time: '',
        type: 995,
        pageNum: 1,
        totalItems: 0,
        ruleIds: '',
        status: '',
      }

      this.secondaryParams = {
        time: '',
        type: 995,
        ruleIds: '',
        status: '',
      }
    },

   /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];
      this.$nextTick(() => {
        this.tableKey = (Math.random() * 1000) >> 2
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    async saveColumnStatusToStorage () {
     const localStorageData = await this.getIndexedDbData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }
      this.saveDataToIndexedDb('columnStatus', columnsStatus);
    },

     /**
     * @description 保存数据到本地indexedDB
     */
    async saveDataToIndexedDb(key, value) {
      const data = await this.getIndexedDbData();
      data[key] = value;
      StorageUtil.storageSet(
        StorageKeyEnum.PerformanceListColumns || 'all',
        data,
        StorageModuleEnum.Performance
      );
    },

        // 构建列
    async buildColumns() {
      const localStorageData = await this.getIndexedDbData();
      let columnStatus = localStorageData.columnStatus || [];

      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let fields = this.getFixedColumns();

      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }

      let columns = fields
        .map(field => {
          // let sortable = false;
          let minWidth = 120;
          return {
            ...field,
            label: field.label,
            field: field.field,
            formType: field.label,
            displayName: field.label,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            // sortable,
            isSystem: field.isSystem,
          };
        })
        .map(col => {
          let show = col.show === true;
          let { width } = col;
          let localField = localColumns[col.field]?.field || null;
          let fixLeft = localField?.fixLeft || null;
          if (null != localField) {
            if (localField.width) {
              width = typeof localField.width == 'number' ? `${localField.width}px` : localField.width;
            }
            show = localField.show !== false;
          } else {
            show = true;
          }
          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left'
          return col;
        });

      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        // 并本地缓存列数据至当前实例的列数据
        this.mergeLocalStorageColumnsToColumns();
      });
    },

    /**
     * @description 合并本地缓存列数据至当前实例的列数据
     */
    async mergeLocalStorageColumnsToColumns() {
      const { columnStatus } = await this.getIndexedDbData();
      if (isEmpty(columnStatus)) return;

      mergeFieldsWithProperty(
        this.columns,
        columnStatus,
        (column, localStorageDataColumnItem) => {
          // 列名不匹配则返回
          if (getFieldName(column) !== getFieldName(localStorageDataColumnItem))
            return;
          // 覆盖列显示状态
          column.show = Boolean(localStorageDataColumnItem.show);
          // 覆盖宽度数据
          if (localStorageDataColumnItem?.width) {
            column.width = localStorageDataColumnItem.width;
          }
        }
      );
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },

    getFixedColumns () {
      return [
        {
          displayName: t('common.base.type'),
          label: t('common.base.type'),
          field: 'type',
          fieldName: 'type',
          show: true,
          width: '70px',
          exportAlias: '',
          export: true,
          tableName: 'performance',
        },
        {
          displayName: t('common.base.name'),
          label: t('common.base.name'),
          field: 'reportName',
          fieldName: 'reportName',
          show: true,
          width: '120px',
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('common.base.createTime'),
          label: t('common.base.createTime'),
          field: 'createTime',
          fieldName: 'createTime',
          show: true,
          width: '100px',
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('common.base.status'),
          label: t('common.base.status'),
          field: 'status',
          fieldName: 'status',

          show: true,
          width: '150px',
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('component.bizBatch.formName'),
          label: t('component.bizBatch.formName'),
          field: 'users',
          fieldName: 'users',
          show: true,
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('performance.displayName.cycle'),
          label: t('performance.displayName.cycle'),
          field: 'cycle',
          fieldName: 'cycle',
          show: true,
          export: true,
          width: '200px',
          tableName: 'performance',

        },
        {
          displayName: t('common.base.createUser'),
          label: t('common.base.createUser'),
          field: 'createUser',
          fieldName: 'createUser',
          show: true,
          width: '100px',
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('performance.label.carbonCopy'),
          label: t('performance.label.carbonCopy'),
          field: 'carbonCopy',
          fieldName: 'carbonCopy',

          show: true,
          width: '100px',
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('performance.displayName.ruleIds'),
          label: t('performance.displayName.ruleIds'),
          field: 'ruleIds',
          fieldName: 'ruleIds',

          show: true,
          exportAlias: 'ruleName',
          export: true,
          tableName: 'performance',

        },
        {
          displayName: t('performance.displayName.action'),
          label: t('performance.displayName.action'),
          field: 'action',
          fieldName: 'action',
          show: true,
          width: '100px',
          tableName: 'performance',
        }
      ]
    },

    // 获取缓存数据
    async getIndexedDbData() {
      let data = {};

      try {
        data = await StorageUtil.storageGet(
          StorageKeyEnum.PerformanceListColumns || 'all',
          {},
          StorageModuleEnum.Performance
        );
      } catch (error) {
        data = {};
        console.error('Caused ~ ArchiveList ~ getIndexedDbData ~ error', error);
      }
      return data;
    },


    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      localStorage.setItem('performance_storage_data_2019_02_28', JSON.stringify(data));
    },
    getLocalStorageData() {
      const dataStr = localStorage.getItem('performance_storage_data_2019_02_28') || '{}';
      return JSON.parse(dataStr);
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：绩效报告-搜索事件');
        return;
      }
      if (type === 'advSearch') {
        window.TDAPP.onEvent('pc：绩效报告-高级搜索事件');
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent('pc：绩效报告-更多操作事件');
        return;
      }
    },

    showAdvancedSetting () {
      window.TDAPP.onEvent('pc：绩效报告-选择列事件');
      this.$refs.advanced.open(this.columns);
    },
    selectionInit(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for(let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.reports.every(report => {
            return report.id !== row.id;
          })
          if(isNotOnCurrentPage) return 
        }

        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];

      }
    },
    selectPerformanceCancel(item) {
      if (!item || !item.id) return;

      this.multipleSelection = this.multipleSelection.filter(ms => ms.id !== item.id);
      this.multipleSelection.length < 1 ? this.selectionInit() : this.selectionInit([item]);
    },
    // 批量匹配选中
    matchSelected() {
      if (!this.multipleSelection.length) return;

      const selected = this.reports
        .filter(c => {
          if (this.multipleSelection.some(sc => sc.id === c.id)) {

            this.multipleSelection = this.multipleSelection.filter(sc => sc.id !== c.id);
            this.multipleSelection.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.selectionInit(selected);
      });
    },
    getRowKey(row) {
      return row.id
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 24 - 10;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
  },
  components: {
    [EditPerformanceReportDialog.name]: EditPerformanceReportDialog,
  }
}
</script>

<style lang="scss">

  html, body, .performance-list-container {
    height: 100%;
  }

  .performance-list-container {
    padding: 10px;

    .base-search {
      background: #fff;
      border-radius: 3px;
      padding: 12px 10px;
    }

    .base-search {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;

      .search-group {
        display: flex;
        justify-content: space-between;
        .el-input {
          width: 300px;
          input {
            height: 34px;
            line-height: 34px;
            width: 300px;
          }
        }
      }

      .advanced-search-visible-btn {
        font-size: 14px;
        line-height: 32px;
        @include fontColor();
        border-color: $color-primary;
        background: #fff;
        padding: 0 13px;
        white-space: nowrap;
        &:hover {
          cursor: pointer;
        }
      }
    }

    .advanced-search-form {
      padding-top: 10px;

      .el-form-item {
        .el-form-item__content,
        .el-select,
        .base-dist-picker,
        .el-cascader,
        .el-date-editor {
          width: 290px;
        }
      }

      .advanced-search-btn-group {
        display: flex;
        justify-content: flex-end;
        width: 100%;
        position: absolute;
        bottom: 0px;
        background: #fff;
        padding: 15px 20px;

        .base-button {
          margin: 0 10px;
        }
      }
    }


    .operation-bar-container {
      background: #fff;
      border-radius: 4px 4px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .top-btn-group .base-button {
        margin-right: 5px;
      }
      .top-btn-group a {
        font-size: 14px;
      }

      .action-button-group {
        .base-button {
          margin-left: 5px;
        }
      }

      .el-dropdown-btn {
        padding: 0 15px;
        line-height: 32px;
        display: inline-block;
        background: $color-primary-light-9;
        color: $text-color-primary;
        outline: none;
        margin-left: 5px;
        .iconfont {
          margin-left: 5px;
          font-size: 12px;
        }

        &:hover {
          cursor: pointer;
          color: #fff;
          background: $color-primary;
        }
      }
    }

    #report-list-1 {
      padding: 0 16px;
    }

    .report-table {
      // padding: 16px;
      &::before {
        content: none;
      }
      th {
        background: #FAFAFA;
        color: $text-color-primary;
        font-weight: normal;
        font-size: 14px;
        line-height: 34px;
        color: #333;
      }
      td {
        font-size: 13px;
      }
    }

    .performance-list {
      background: #fff;
      border-radius: 4px;
      .performance-report-table-pagination {
        text-align: right;
      }
    }

    .customer-table-pagination {
      text-align: right;
      padding: 10px 5px;
    }
  }

  .performance-list-table-footer {
    background: #fff;
    border-radius: 0 0 3px 3px;

    display: flex;
    justify-content: space-between;

    padding: 0px 10px 10px 10px ;

    .list-info {
      color: #767e89;

      font-size: 13px;
      line-height: 48px;

      margin: 0;

      .iconfont {
        position: relative;
        top: 1px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }

  // performance selected panel
  .performance-selected-count{
    cursor: pointer;
    @include fontColor();

    font-size: 13px;

    padding: 0 3px;
    width: 15px;

    text-align: center;
  }

  .performance-panel {
    .base-panel-title {
      h3 {
        display: flex;
        justify-content: space-between;
        i {
          cursor: pointer;
          display: inline-block;
          text-align: center;
          &:hover {
            @include fontColor();
          }
        }
      }
    }
  }

  .performance-selected-panel{
    font-size: 14px;
    height: calc(100% - 51px);
  }

  .performance-selected-tip{
    padding-top: 80px;

    img{
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p{
      color: $text-color-regular;

      line-height: 20px;
      text-align: center;

      margin: 8px 0 0 0;
    }
  }

  .performance-selected-list{
    height: 100%;
    padding: 10px;
    overflow-y: auto;
  }

  .performance-selected-row{
    border-bottom: 1px solid #ebeef5;

    display: flex;
    flex-flow: row nowrap;

    font-size: 13px;
    line-height: 36px;


    &:hover{
      background-color: #f5f7fa;

      .performance-selected-delete{
        visibility: visible;
      }
    }
  }

  .performance-selected-head{
    background-color: #F0F5F5;
    color: #333;
    font-size: 14px;
  }

  .performance-selected-name{
    padding-left: 10px;
    flex: 1;
    @include text-ellipsis;
  }

  .performance-selected-type{
    padding-left: 10px;
    width: 150px;
    @include text-ellipsis;
  }

  .performance-selected-delete{
    width: 36px;
  }

  .performance-selected-row button.performance-selected-delete{
    background-color: transparent;
    color: #646B78;

    border: none;
    
    padding: 0;
    width: 36px;
    height: 36px;

    outline: none;
    visibility: hidden;

    i{
      font-size: 14px;
    }

    &:hover{
      color: #e84040;
    }
  }

  .performance-list {
    .open-data {
      margin-right: 0;
    }
  }

</style>
